<template>
	<div class="app-container">
		<!-- 		
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="openZip = true"
>导入</el-button>
			</el-col>
		</el-row> -->
		<div class="home-center-box">
			
			<div style="flex: 1;margin: 8%;">
				<el-card class="box-card" v-for="(item,key) in list" :key="key"
					style="width: calc(20% - 20px);margin: 10px;float: left;">
					<div slot="header" class="clearfix">
						<span>{{item.taskName}}</span>
						<el-button style="float: right; padding: 3px 0" type="text"
							@click="setCentent(item)">开始填报</el-button>
						<el-button style="float: right; padding: 3px 0" type="text"
							@click="exportLocalFile(item)">导出数据包</el-button>
					</div>
					<div style="margin-bottom:15px">任务描述：{{item.taskDesc}}</div>
					<div style="margin-bottom:15px">开始时间：{{item.startTime}}</div>
					<div style="margin-bottom:15px">任务状态：{{item.temaplateType == 1?'已填报':'未填报'}}</div>
				</el-card>
			</div>
		</div>
		<!-- 		<div class="daoru-box">
			<div class="left">
				<input type="file" @change="daoru" accept=".zip" multiple ref="fileInput"
					style="width: 100%;height: 100%;opacity: 0;position: absolute;left: 0;top: 0;right: 0;bottom: 0;" />
				<div>导入</div>
			</div> -->
		<!--			<div class="left">-->
		<!--				<div @click="importLocalFile">测试本地文件导入</div>-->
		<!--			</div>-->

		<!--      <div class="left">-->
		<!--        <div>填报后导入-->
		<!--          <el-upload style=""-->
		<!--                     class="upload-demo"-->
		<!--                     ref="upload"-->
		<!--                     :limit="10"-->
		<!--                     drag-->
		<!--                     action="#"-->
		<!--                     :http-request="importLocalFile1"-->
		<!--                     accept=".zip"-->
		<!--                     :multiple="true">-->
		<!--            <i class="el-icon-upload"></i>-->
		<!--            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>-->
		<!--          </el-upload>-->
		<!--        </div>-->
		<!--      </div>-->

		<!--      <div class="left">-->
		<!--        <div @click="exportLocalFile">测试本地文件导出</div>-->
		<!--      </div>-->
		<!-- </div> -->
		
		<div class="daoru-box">
				<input type="file" @change="daoru" accept=".zip" multiple ref="fileInput"
					style="width: 100%;height: 100%;opacity: 0;position: absolute;left: 0;top: 0;right: 0;bottom: 0;" />
		</div>
		
		<myDrawer ref="myDrawer" @ok="drawerOk" :headerBtnShow="false">
			<template #center>
				<modelForm ref="modelForm" @ok="modelFormOk"></modelForm>
			</template>
		</myDrawer>

		<el-dialog :title="title" :visible.sync="openZip" width="600px" append-to-body :before-close="closeOpen">
		</el-dialog>
		<Full ref="full" style="display: none;" @uploadOk="uploadOk" />
		<myFileUpload ref="myFileUpload"></myFileUpload>
	</div>
</template>

<script>
	import {
		getAction,
		postAction,
		editAction,
		removeAction,
		detailAction,
	} from "@/api/api";
	import mylog from '@/views/components/mylog.vue'
	import myDrawer from '@/views/components/myDrawer.vue'
	import myFileUpload from '@/views/components/myFileUpload.vue'
	import task from '@/views/lanjing/task/index.vue'
	import modelForm from '@/views/lanjing/import/modelForm.vue'
	import dept from '@/views/lanjing/task/dept.vue'
	import Full from "./full";

	import taskApi from '@/api/task';
	import deptApi from '@/api/dept';
	import taskdeptApi from '@/api/taskdept';
	import roundApi from '@/api/round';
	import matterApi from '@/api/matter';
	import fankuiApi from '@/api/fankui';
	import shenheApi from '@/api/shenhe';

	import zipApi from '@/api/jszipApi';
	import {
		mixin
	} from '@/mixins/mixins';
	import {
		app,
		dialog
	} from "@electron/remote";
	import {
		name as pkgName
	} from "../../../../../package.json";

	const fs = require('fs');
	const path = require('path');
	const appDataPath = app.getPath('appData')
	const appFilePath = path.join(appDataPath, `/${pkgName}`)
	export default {
		dicts: ['model_type'],
		mixins: [mixin],
		components: {
			mylog,
			myDrawer,
			task,
			modelForm,
			dept,
			Full,
			myFileUpload
		},
		name: "Template",
		data() {
			return {
				fileList: [],
				// 导出路径
				userDataPath: '',
				exportPath: '',

				temaplateTypes: [{
						label: '未发布',
						value: 0,
					},
					{
						label: '已发布',
						value: 1,
					}
				],
				// 显示搜索条件
				showSearch: true,
				openZip: false,
				// 查询参数
				queryParams: {
					page: 1,
					rowsPerPage: 10,
					pageSize: 10,
					temaplateName: null,
					temaplateDesc: null,
					temaplateType: null,
					temaplateBackup1: null,
					temaplateBackup2: null,
					temaplateBackup3: null,
					temaplateBackup4: null,
					ancestors: null,
					// temaplateTop: 1,
					temaplateFankui: null,
					temaplatePingfen: null,
					parentIds: [],
					idd: null
				},
				// 表单校验
				rules: {},
				//自动调用GetList
				autoGetList: false,
				//接口名称
				apiUrl: '/lanjing/round',
				rowForm: null,
				btnShow: true,
				waitFileList: [],
				fileIndex: 0,
			};
		},
		created() {
			this.loading = false;
			this.pageNum = '任务'
			this.getList()
			// this.$nextTick(() => {
			// 	this.$refs.dept.getList();
			// })
		},
		mounted() {
			this.getUserDataPath()
		},
		methods: {
			getUserDataPath() {
				// 存放文件路径
				this.exportPath = appFilePath + '/taskFile'

			},
			listMap(e) {
				e = e.map(v => {
					let obj = {
						...v
					}
					if (obj.temaplateBackup1) {
						obj.temaplateBackup1 = true
					}
					return obj
				})
				return e
			},

			// 表单重置
			reset() {
				this.form = {
					id: null,
					temaplateName: null,
					temaplateDesc: null,
					temaplateType: null,
					temaplateBackup1: null,
					temaplateBackup2: null,
					temaplateBackup3: null,
					temaplateBackup4: null,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null,
					remark: null,
					parentId: 0,
					ancestors: null,
					temaplateTop: 1,
					temaplateFankui: null,
					temaplatePingfen: null
				};
				this.resetForm("form");
			},
			// 多选框选中数据
			handleSelectionChange(selection) {
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			load(tree, treeNode, resolve) {
				console.log(tree, treeNode)
				getAction(`${this.apiUrl}/list`, {
					parentId: tree.id,
					pageNum: 1,
					pageSize: 999,
				}).then(res => {
					resolve(res.rows);
				})
			},
			addDpet(row) {
				// this.rowForm = row
				this.reset();
				//idd 父级Id
				if (row.parentId === 0) {
					let obj = null
					if (row.temaplateBackup2) {
						obj = JSON.parse(row.temaplateBackup2)
					}
					//判断第一级自增id
					this.form.iid = !obj ? 1 : obj.length
					//传入模板id
					this.form.parentIds = [row.id]
					// this.form.parentIds  = [row.idd]
				} else {


				}
				this.handleAdd(false)
			},
			updataParentId() {
				this.submitForm()
			},
			setCentent(row) {
				this.$refs.myDrawer.open = true;
				this.$refs.myDrawer.title = `【${row.taskName}】编辑轮次配置`;

				this.btnShow = row.temaplateType == 1 ? false : true;
				this.$nextTick(() => {
					if (row.id) {
						roundApi.getModelById(row.id).then(async res => {
							// let userInfo = this.$store.state.user.userInfo
							let taskdeptApiData = await taskdeptApi.getModelPagination({
								page: 1,
								rowsPerPage: -1
							}, null, {
								roundId: row.id
							})
							console.log('11111111111111111111', taskdeptApiData)
							let taskApiData = await taskApi.getModelPagination({
								page: 1,
								rowsPerPage: -1
							}, null, {
								topTaskid: row.id
							})
							taskdeptApiData = taskdeptApiData.data.list
							console.log('11111111111111111111', taskdeptApiData)
							taskApiData = taskApiData.data.list
							taskApiData = taskApiData.map(v => {
								let guanlian = taskdeptApiData.find(d => d.taskId == v.id)
								let obj = {
									...v,
									nodeQianzhi: !v.taskBackup1 ? null : JSON.parse(v
										.taskBackup1),
									guanlian
								}
								return obj
							})
							console.log(taskApiData)
							res.data.temaplateTask = JSON.stringify(taskApiData)
							this.$refs.modelForm.setRowInfo(res.data)
						})
					}
					// })
				})
			},
			drawerOk() {
				this.$refs.modelForm.getDataObj()
			},
			modelFormOk(e) {
				//派发任务接口
				editAction(this.apiUrl, e).then(res => {
					if (res.code == 200) {
						this.$message.success('保存成功')
						this.$refs.myDrawer.cancel()
					}
				})

			},
			startModel(row) {
				postAction(`/lanjing/task/paifaSave`, {
					...row
				}).then(response => {
					if (res.code == 200) {
						this.$message.success('发布成功')
						this.getList()
					}
				});
			},
			daoru(e) {
				console.log(e.target.files)
				if (e.target.files) {
					this.loading = true;
					this.fileIndex = 0
					this.waitFileList = e.target.files
					this.uploadFileList()
				}
			},
			uploadFileList() {
				this.$refs.full.httpRequest(this.waitFileList[this.fileIndex])
			},
			uploadOk(type) {
				if (type) {
					if (this.waitFileList.length - 1 == this.fileIndex) {
						this.$refs.fileInput.value = null
					} else {
						this.fileIndex++
						this.uploadFileList()
					}
				} else {
					this.waitFileList = []
					this.fileIndex = 0
					this.$refs.fileInput.value = null
				}
			},
			showDrawer(id = null) {
				this.loading = false;
				if (id) {
					roundApi.getModelById(id).then(res => {
						console.log(res)
						this.setCentent(res.data)
					})
				}
			},

			//导出压缩包
			exportLocalFile(row) {
				// const rootFolder= "C:\\Users\\ghy\\AppData\\Roaming\\adxczg\\taskFile";
				//zip.file("data.json", Encrypt(JSON.stringify(sjson)));
				// 遍历根文件夹内的文件夹
				var dataJson = {};
				var deptIds = 104;
				// 使用加密狗里的部门id 查询部门数据  测试 104
				console.log(row)
				// 查询部门
				deptApi.getModelWhere({
					deptId: 104
				}).then(res => {
					if (res.code == 200) {
						console.log(res.data[0])
						this.$set(dataJson, "dept", res.data[0])
					}
				});
				//查询轮次
				roundApi.getModelById(row.id).then(async res => {
					console.log('000000', res.data)
					this.$set(dataJson, "patrolRound", res.data)

					let taskApiData = await taskApi.getModelWhere({
						topTaskid: row.id
					})
					this.$set(dataJson, "patrolTaskList", taskApiData.data)
					console.log('111', taskApiData)
					// 中间表
					let taskdeptApiData = await taskdeptApi.getModelWhere({
						roundId: row.id,
						deptId: deptIds
					})
					this.$set(dataJson, "patrolTaskDeptList", taskdeptApiData.data)
					console.log('22', taskdeptApiData)
					// 根据轮次查询反馈和 评分和

					let matterApiata = await matterApi.getModelWhere({
						roundId: row.id,
						deptId: deptIds
					})

					this.$set(dataJson, "matterList", matterApiata.data)
					console.log(matterApiata)
					let fankuiApiata = await matterApi.getModelWhere({
						roundId: row.id,
						deptId: deptIds
					})
					this.$set(dataJson, "fankuiList", fankuiApiata.data)
					console.log(fankuiApiata)
					let shenheApiata = await matterApi.getModelWhere({
						roundId: row.id,
						deptId: deptIds
					})
					this.$set(dataJson, "shenheList", shenheApiata.data)
					console.log(shenheApiata)

           console.log(dataJson)
          zipApi.startZIP(row,dataJson);
        })
			},
			importLocalFile() {
				this.$refs.myFileUpload.importLocalFile()
			},

			importLocalFile1(file) {
				zipApi.endZIP(file);
			}
		}
	};
</script>
<style scoped lang="scss">
	.app-container {
		height: calc(100vh - 100px);
	}

	.daoru-box {
		position: fixed;bottom: 40px;left: calc(50% - 450px);right: calc(50% - 450px);width: 900px;height: 120px;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		background-image: url('/src/renderer/assets/images/btn.png');
		background-size: 100% 100%;
		
	}

	.home-center-box {
		background-image: url('/src/renderer/assets/images/index-bg.png');
		background-size: 100% 100%;
		height: 100%;
		overflow-x: hidden;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}
	.el-card{
		background-color: rgba(12, 25, 33,0.8);
		border: none;
		border-radius: 10px;
		
		*{
			color: #ffffff;
		}
	}
	::v-deep .el-card__header{
		border-bottom: none !important;
	}
</style>